"use strict";

import {
    //核心
    React, Enhance, Controller, Component, $, EventEmitter,
    //
    tools, classnames,
    // 组件
    Table, TabPage, Lang, Dialog, Tree,
    Form, Page, Upload, Icon, Grid,
    BoxWidget, Input, Button, Prompt, Link, Loaders, Editor, Resource, Directive, Lock, Fix, Http
} from 'admin';

import Project from '../widget/w-project';

var { http, date, time } = tools;
const log = debug('ysw.project');

/**
 * 工时标准
 */
class ProjectController extends Controller {
    state = {
        table: {
            update: {},
            query: {},
            types: {
            },
            onRowClick: this._handlerRowClick,
            buttons: {
                'edit': {
                    onClick: this._handlerEditDialog
                },
                'set_item': {
                    icon: {
                        icon: 'settings',
                        type: 'admin'
                    },
                    onClick: this._handlergoodsDialog
                },
            },
            pk: 'id',
            fields: [
                {
                    title: "#",
                    width: 1,
                    type: {
                        name: "#"
                    }
                },
                {
                    order: -1,
                    name: 'id',
                    width: 1,
                    display: false
                },
                {
                    order: 0,
                    name: 'code',

                },
                {
                    name: 'name',
                    order: 0,
                },
                {
                    order: 0,
                    name: 'desc',

                },
                {
                    name: 'work',
                    order: 0,
                },

            ]
        },
        table_item: {
            autoLoad: false,
            length: 100,
            // action: "get_itemlist",
            buttons: {
                'add': {
                    onClick: this._handleraddmove,
                    onDisplay: (data)=> {
                        return !this.state.itemlist[data.id];
                    }
                }
            },
            fields: [
                {
                    title: "#",
                    width: 1,
                    type: {
                        name: "#"
                    }
                },
                {
                    order: -1,
                    name: 'id',
                    width: 1,
                    display: false
                },
                {
                    order: 0,
                    name: 'code'
                },
                {
                    name: 'name',
                    order: 0,
                },
                {
                    order: 0,
                    name: 'origin'
                },
                {
                    name: 'model',
                    order: 0,
                },
                {
                    order: 0,
                    name: 'unit'
                }

            ]
        },
        table_item2: {
            autoLoad: false,
            length: 100,
            // action: "get_itemlist",
            // buttons: {
            //     'add': {
            //         onClick: this._handleraddmove2,
            //         onDisplay: (data)=> {
            //             return !this.state.itemlist[data.id];
            //         }
            //     }
            // },
            types: {
                type: function (data, options) {
                    if (data.val == 2)
                        return <span className='label bg-green'>己绑</span>;
                    if (data.val == 1)
                        return <span className='label bg-red'>未绑</span>;
                }
            },
            fields: [
                {
                    title: "#",
                    width: 1,
                    type: {
                        name: "#"
                    }
                },
                {
                    order: 0,
                    name: 'code'
                },
                {
                    name: 'name',
                    order: 0,
                },
                {
                    order: 0,
                    name: 'number'
                },
                {
                    order: 0,
                    name: 'unit'
                },
                {
                    order: 0,
                    name: 'tag',
                    type: {
                        name: 'type'
                    }
                }
            ]
        },
        row: {},
        edit: {},
        itemlist:{},
        searchlist:{}
    }

    /**
     * 在componentWillMount()在挂载发生之前立即被调用。
     */
    componentWillMount() {

    }

    /**
     *
     */
    constructor() {
        super();
    }

    render() {
        return (
            <Grid>
                <Grid col="12 12 12 12">
                    {this.renderTable()}
                </Grid>
                {this.renderAddDialog()}
                {this.rendersetgoodsDialog()}
                <Project ref="project" onCache={() => { this.forceUpdate() }} onAddSuccess={this._handlerAddSuccess} onEditSuccess={this._handlerEditSuccess}></Project>
            </Grid>
        );
    }

    rendersetgoodsDialog() {
        let list = [],num = [];
        let {itemlist}=this.state;
        $.each(itemlist, (k, v)=> {
            if(v && v.tag == 1){
                list.push(v.id);
                num.push(v.number);
            }
        })
        return (
            <Directive name="Modal">
                <Dialog
                    title={this._lang('set_item')}
                    ref="setgoodsDialog"
                    size="2"
                >
                    <div data-fix="elem">
                        <Form
                            rules={{}}
                            action={this._action('do_set_item')}
                            onSuccess={this._handlersetgoodsSuccess}
                        />
                    </div>
                    <div data-fix="content">
                        <Grid>
                            <Grid>
                                <Input type="hidden" name="id" value={this.state.addData}/>
                                <Input type="hidden" name="items" value={list.join(',')}/>
                                <Input type="hidden" name="number" value={num.join(',')}/>
                                <Grid col="12 12 12 12">
                                    <Input type="text" name="item_id"
                                           message={this._lang('code')}
                                           onChange={this._handleritemCahnge}
                                    />
                                </Grid>
                            </Grid>
                            {this.renderTablesetitem()}
                            {this.renderCustlistitem()}
                        </Grid>
                    </div>

                </Dialog>
            </Directive>
        );
    }

    renderTablesetitem() {
        let data = [];
        $.each(this.state.searchlist, (k, v)=> {
            if(v){data.push(v)}
        })
        return (
            <Grid col="12 12 6 6">
                <BoxWidget
                    color="3"
                    className="table-height scroll"
                >
                    <div data-fix="content">
                        <Table ref="table_item" data={data} {...this.props} {...this.state.table_item}/>
                    </div>

                </BoxWidget>
            </Grid>
        );
    }

    renderCustlistitem() {
        let data = [];
        $.each(this.state.itemlist, (k, v)=> {
            if(v){data.push(v)}
        })
        return (
            <Grid col="12 12 6 6">
                <BoxWidget
                    title={'绑定配件列表'}
                    className="table-height scroll"
                    color="3"
                >
                    <div data-fix="buttons">
                        <Button type="submit">
                            <Lang lang="submit"/>
                        </Button>
                    </div>
                    <div data-fix="content">
                        <Table
                            data={data}
                            {...this.props}
                            {...this.state.table_item2}
                            buttons={{
                                'delete': {
                                    onClick: (data)=>{
                                        if(data.tag == 2){
                                            this._emit("Confirm", {
                                                title: '是否删除绑定的配件： ' + data.name, onConfirm: (close) => {
                                                    this.refs.http.send(this._action('do_delete_item'), {
                                                        id: data.f_id
                                                    })
                                                        .success((res) => {
                                                            if (res) {
                                                                delete this.state.itemlist[data.id];
                                                                this.forceUpdate();
                                                                window.toast(<Lang lang="message.success.delete"/>);
                                                            } else {
                                                                window.toast(<Lang lang="message.error.delete"/>);
                                                            }
                                                        })
                                                }
                                            })
                                        }else if(data.tag == 1){
                                            delete this.state.itemlist[data.id];
                                            this.forceUpdate();
                                        }

                                    }
                                }}
                            }/>
                    </div>
                </BoxWidget>
            </Grid>
        );
    }
    /**
     *
     * @return {*}
     */
    renderTable() {
        return (
            <BoxWidget
                color="3"
                className="table-height scroll"
            >
                <div data-fix="buttons">
                    <Button onClick={this._handlerAddDialog}>
                        <Icon icon="add"></Icon>
                        <Lang lang="add"></Lang>
                    </Button>
                </div>
                <div data-fix="content">
                    <Http ref="http"/>
                    <Lock>
                        <Table ref="table" {...this.props} {...this.state.table} />
                    </Lock>
                </div>
            </BoxWidget>
        );
    }

    renderAddDialog() {
        let {row} = this.state;
        return (
            <Directive name="Modal">
                <Dialog
                    ref="addDialog"
                    title={this._lang("add")}
                >
                    <div data-fix="elem">
                        <Form
                            action={this._action('get_fitting')}
                            onSuccess={this._handlerSetFitting}
                            rules={{
                                "number": "required|int",
                            }}
                        />
                    </div>
                    <div data-fix="content">
                        <Input name="id" type="hidden" model={row} />
                        <Input name="tag" type="hidden" model={row} />
                        <Input type="text" name="code" message={this._lang("code")} model={row}/>
                        <Input type="text" name="name" message={this._lang("name")} model={row}/>
                        <Input type="number" name="number" message={this._lang("number")}/>
                        <Input type="text" name="unit" message={this._lang("unit")} model={row}/>
                        <Input type="text" name="origin" message={this._lang("origin")} model={row}/>
                        <Input type="text" name="model" message={this._lang("model")} model={row}/>
                    </div>
                    <div data-fix="buttons">
                        <Button type="submit">
                            <Lang lang="submit"></Lang>
                        </Button>
                    </div>
                </Dialog>
            </Directive>
        );
    }

    _handlerSetFitting(data) {
        if (data) {
            this.state.itemlist[data.id] = data;
            this.forceUpdate();
            this.refs.addDialog.hide();
        }
    }

    _handleraddmove(row) {
        this.setState({row}, function () {
            this.refs.addDialog.show();
        })
    }

    _handlergoodsDialog(data) {
        this.state.addData = data.id;
        this.refs.http
            .send(this._action('get_item'), {id: data.id})
            .success((list)=> {
                this.setState({itemlist: list|| {},searchlist: {}}, ()=> {
                    this.refs.setgoodsDialog.show();
                })
            });
    }

    _handleritemCahnge(e) {
        this.clear(this.state.item_timer);
        this.state.item_id = e.target.value;
        this.state.item_timer = setTimeout(()=>{
            // this.refs.table_item.query({code: this.state.item_id});
            this.refs.http
                .send(this._action('get_itemlist'), {code: this.state.item_id})
                .success((list)=> {
                    this.setState({searchlist:list|| {}})
                });
        },500)

    }
    /**
     *
     * @private
     */
    _handlerAddDialog() {
        this.refs.project.showAddDialog()
    }

    /**
     *
     * @param edit
     * @private
     */
    _handlerEditDialog(edit) {
        this.setState({ edit }, function () {
            this.refs.project.showEditDialog(this.state.edit)
        })
    }

    /**
     *
     * @param data
     * @private
     */
    _handlerAddSuccess(data) {
        if (data) {
            this.refs.table.append(data);


        }
    }


    /**
     *
     * @param update
     * @private
     */
    _handlerEditSuccess(data) {
        if (data) {
            this.refs.table.update(data);
        }
    }

    _handlersetgoodsSuccess(data) {
        if (data) {
            this.refs.setgoodsDialog.hide();
            window.toast(<Lang lang="message.success.set_item"/>)
        } else {
            window.toast(<Lang lang="message.error.set_item"/>)
        }
    }
}

export default Enhance(ProjectController);
